<template>
  <div class="picture-list">
    <a-list
      :grid="{ gutter: 16, xs: 1, sm: 2, md: 3, lg: 4, xl: 5, xxl: 6 }"
      :data-source="dataList"
      :loading="loading"
    >
      <template #renderItem="{ item: picture }">
        <a-list-item style="padding: 0">
          <div class="card-wrapper">
            <a-checkbox
              :class="['batch-checkbox', { 'is-checked': isSelected(picture) }]"
              :checked="isSelected(picture)"
              @change="(e) => handleCheckboxChange(picture, e)"
              @click.stop
            />
            <a-card hoverable @click="doClickPicture(picture)">
              <template #cover>
                <img
                  :alt="picture.name"
                  :src="picture.thumbnailUrl ?? picture.url"
                  style="height: 180px; object-fit: cover"
                />
              </template>
              <a-card-meta :title="picture.name">
                <template #description>
                  <a-flex>
                    <a-tag color="green">
                      {{ picture.category ?? '默认' }}
                    </a-tag>
                    <a-tag v-for="tag in picture.tags" :key="tag">
                      {{ tag }}
                    </a-tag>
                  </a-flex>
                </template>
              </a-card-meta>
              <template v-if="showOp" #actions>
                <a-tooltip title="分享图片">
                  <ShareAltOutlined @click="(e) => doShare(picture, e)" />
                </a-tooltip>
                <a-tooltip title="以图搜图">
                  <SearchOutlined @click="(e) => doSearch(picture, e)" />
                </a-tooltip>
                <a-tooltip v-if="canEdit" title="编辑图片">
                  <EditOutlined @click="(e) => doEdit(picture, e)" />
                </a-tooltip>
                <a-tooltip v-if="canDelete" title="删除图片">
                  <DeleteOutlined @click="(e) => doDelete(picture, e)" />
                </a-tooltip>
              </template>
            </a-card>
          </div>
        </a-list-item>
      </template>
    </a-list>
    <ShareModal ref="shareModalRef" :link="shareLink" />
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import {
  DeleteOutlined,
  EditOutlined,
  SearchOutlined,
  ShareAltOutlined,
} from '@ant-design/icons-vue'
import { deletePictureUsingPost } from '@/api/pictureController'
import { message } from 'ant-design-vue'
import ShareModal from '@/components/ShareModal.vue'
import { ref } from 'vue'
import { CheckboxChangeEvent } from 'ant-design-vue/es/checkbox/interface'

interface Props {
  dataList?: API.PictureVO[]
  loading?: boolean
  showOp?: boolean
  canEdit?: boolean
  canDelete?: boolean
  onReload?: () => void
  // 从父组件接收已选中的ID列表
  selectedPictureIds?: (string | number)[]
}

// 定义emit，用于向父组件发送更新
const emit = defineEmits(['update:selectedPictureIds'])

const props = withDefaults(defineProps<Props>(), {
  dataList: () => [],
  loading: false,
  showOp: false,
  canEdit: false,
  canDelete: false,
  selectedPictureIds: () => [],
})

// 检查图片是否被选中
const isSelected = (picture: API.PictureVO) => {
  return props.selectedPictureIds.includes(picture.id)
}

// 处理复选框状态变更，并通知父组件
const handleCheckboxChange = (picture: API.PictureVO, e: CheckboxChangeEvent) => {
  const isChecked = e.target.checked
  const newSelectedIds = [...props.selectedPictureIds]
  if (isChecked) {
    if (!newSelectedIds.includes(picture.id)) {
      newSelectedIds.push(picture.id)
    }
  } else {
    const index = newSelectedIds.indexOf(picture.id)
    if (index > -1) {
      newSelectedIds.splice(index, 1)
    }
  }
  emit('update:selectedPictureIds', newSelectedIds)
}

const router = useRouter()
// 跳转至图片详情页
const doClickPicture = (picture: API.PictureVO) => {
  router.push({
    path: `/picture/${picture.id}`,
  })
}

// 搜索
const doSearch = (picture: API.PictureVO, e: Event) => {
  // 阻止冒泡
  e.stopPropagation()
  // 打开新的页面
  window.open(`/search_picture?pictureId=${picture.id}`)
}

// 编辑
const doEdit = (picture: API.PictureVO, e: Event) => {
  // 阻止冒泡
  e.stopPropagation()
  // 跳转时一定要携带 spaceId
  router.push({
    path: '/add_picture',
    query: {
      id: picture.id,
      spaceId: picture.spaceId,
    },
  })
}

// 删除数据
const doDelete = async (picture: API.PictureVO, e: Event) => {
  // 阻止冒泡
  e.stopPropagation()
  const id = picture.id
  if (!id) {
    return
  }
  const res = await deletePictureUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    props.onReload?.()
  } else {
    message.error('删除失败')
  }
}

// ----- 分享操作 ----
const shareModalRef = ref()
// 分享链接
const shareLink = ref<string>()
// 分享
const doShare = (picture: API.PictureVO, e: Event) => {
  // 阻止冒泡
  e.stopPropagation()
  shareLink.value = `${window.location.protocol}//${window.location.host}/picture/${picture.id}`
  if (shareModalRef.value) {
    shareModalRef.value.openModal()
  }
}
</script>

<style scoped>
.card-wrapper {
  position: relative;
  width: 100%;
}

.batch-checkbox {
  position: absolute;
  top: 12px;
  right: 12px;
  z-index: 10;
  /* 默认隐藏复选框 */
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  padding: 2px;
}

/* 卡片悬停时显示复选框 */
.card-wrapper:hover .batch-checkbox {
  opacity: 1;
}

/* 如果复选框已被选中，则保持可见 */
.batch-checkbox.is-checked {
  opacity: 1;
}
</style>
